import { insertIntoTextarea } from '@gnlab/utils/env-browser/dom'
import { Input, Button } from 'antd'
import type { TextAreaRef } from 'antd/lib/input/TextArea'
import type { TextWord } from '@/services/common/definition'
import './index.module.less'

export default function EditText(props: {
  word: TextWord
  variables?: { name: string; symbol: string }[]
  variablesLabel?: React.ReactNode
  onSave: (word: TextWord) => void
  onCancel: () => void
}) {
  const { word: initialWord, variables = [], variablesLabel = null, onSave, onCancel } = props

  const [word, setWord] = useState(initialWord)
  const onChange = useCallback(
    (e: React.ChangeEvent<HTMLTextAreaElement>) => setWord({ ...word, text: e.target.value }),
    [word],
  )

  const inputRef = useRef<TextAreaRef>(null)
  const insertVariable = useCallback(
    (variable: string) => {
      const textarea = inputRef.current?.resizableTextArea?.textArea
      if (!textarea) return
      const result = insertIntoTextarea(textarea, variable)
      setWord(word => ({ ...word, text: result }))
    },
    [inputRef],
  )

  return <>
    <main styleName="edit-text">
      <Input.TextArea rows={8} value={word.text} onChange={onChange} ref={inputRef} />

      {variables.length ? (
        <div styleName="variables">
          {variablesLabel}
          {variables.map(({ name, symbol }) => <a key={name} onClick={() => insertVariable(symbol)}>
            {name}
          </a>)}
        </div>
      ) : null}
    </main>
    <footer>
      <Button onClick={onCancel}>取消</Button>
      <Button type="primary" disabled={!word.text.length} onClick={() => onSave(word)}>
        保存
      </Button>
    </footer>
  </>
}
